package br.com.ads.sgse.managedBean;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.persistence.EntityManager;
import javax.persistence.Query;



import br.com.ads.dao.DAO;
import br.com.ads.dao.JPAUltil;
import br.com.ads.sgse.entity.DisciplinaTurma;
import br.com.ads.sgse.entity.Turma;

@ManagedBean(name="turmaBean")
@ViewScoped
public class TurmaBean {
	private Turma turma = new Turma();
	
	private List<Turma> turmas;
	
	private DAO<Turma> dao = new DAO<Turma>(Turma.class);
	
	private DisciplinaTurma disciplinaTurma = new DisciplinaTurma();
	
	
	
	private Long disciplinaId;
	
	private EntityManager em = new JPAUltil().getEntityManager();
	
	private String parameter;

	public String getParameter() {return parameter;}
	public void setParameter(String parameter) {this.parameter = parameter;}

	/** ACTIONS **/

	@SuppressWarnings("unused")
	@PostConstruct
	private void init() {
		getAllTurmas();
	}

	public void addVinculo() {
		//disciplinaTurma.setDisciplina(daodisciplinas.buscaPorId(disciplinaId));
		if(!turma.getDisciplinaturmas().contains( disciplinaTurma)) {
			 disciplinaTurma.setTurma(turma);
			turma.getDisciplinaturmas().add( disciplinaTurma);
		}
		 disciplinaTurma= new DisciplinaTurma();
	}
	
		
	public String salvar() {
		try {
			if (turma.getId() == null) {
				dao.adiciona(turma);
			} else {
				dao.atualiza(turma);
			}

			getAllTurmas();
			turma = new Turma();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public void remove() {
		try {
			dao.remove(turma);
			getAllTurmas();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void getAllTurmas() {
		try {
			setTurmas(dao.listaTodos());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
		public void getTurmaByNumero() {
		try {
			Query q = em.createQuery("SELECT nf FROM Turma nf WHERE nf.numero=:numero");
			q.setParameter("numero", new Long(parameter));
			turma = (Turma) q.getSingleResult();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

	public Turma getTurma() {return turma;}
	public void setTurma(Turma turma) {this.turma = turma;}
	
	public void setTurmas(List<Turma> turmas) {this.turmas = turmas;}
	public List<Turma> getTurmas() {return turmas;}
	
	public DisciplinaTurma getdisciplinaTurma() {return disciplinaTurma;}
	public void setdisciplinaTurma(DisciplinaTurma disciplinaTurma) {this.disciplinaTurma = disciplinaTurma;}
	
	public Long getDisciplinaId() {return disciplinaId;}
	public void setDisciplinaId(Long disciplinaId) {this.disciplinaId = disciplinaId;}
	

}
